<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/13
 * Time: 17:26
 */

namespace app\admin\model;

use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\model\relation\HasMany;

/**
 * @property  int $id
 * @property  string $no
 */
class Goods extends BaseModel
{

    /**
     * 关联商品规则表
     * @return HasMany
     */
    public function goodsRule(): HasMany
    {
        return $this->hasMany(GoodsRule::class);
    }

    /**
     * 关联商品规则组表
     * @return HasMany
     */
    public function spec(): HasMany
    {
        return $this->hasMany(Spec::class);
    }

    public static function onBeforeInsert(Goods $model)
    {
        $model->no = "HCYT-SP-" . time().rand(10,99);
    }


    /**
     * @param Goods $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onAfterInsert(Goods $model): void
    {
        $param = Request::param();
        //规格组处理
        if ($param['attrs']) {
            foreach ($param['attrs'] as $k => $v) {
                if (!$Spec = Spec::where('goods_id', $model->id)->where('name', $k)->find()) {
                    $Spec = new Spec();
                }
                $arr['goods_id'] = $model->id;
                $arr['name']     = $k;
                $arr['value']    = $v;
                $Spec->save($arr);
            }
        }
        //添加商品规格
        foreach ($param['specs'] as &$v) {
            $v['goods_id'] = $model->id;
        }
        (new GoodsRule)->saveAll($param['specs']);
    }


    /**
     * @param Goods $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onBeforeUpdate(Goods $model): void
    {

        $param = Request::param();
        //规格组处理
        if (request()->param('attrs', 0)) {
            foreach ($param['attrs'] as $k => $v) {
                if (!$Spec = Spec::where('goods_id', $model->id)->where('name', $k)->find()) {
                    $Spec = new Spec();
                }
                $arr['goods_id'] = $model->id;
                $arr['name']     = $k;
                $arr['value']    = $v;
                $Spec->save($arr);
            }
        }
        //添加商品规格
        foreach ($param['specs'] as &$v) {
            if (!$goodsRule = GoodsRule::where('spec_name', $v['spec_name'])->where('goods_id', $model->id)->find()) {
                $goodsRule = new GoodsRule();
            }
            $v['goods_id'] = $model->id;
            $goodsRule->save($v);
        }
    }

}